﻿#region

using System.Security.Cryptography;
using System.Text;

#endregion

namespace Vin.Tool.Core.EncryptCategory;

public class AesEncryptTool
{
    /// <summary>
    /// AES加密
    /// </summary>
    public static string AesEncrypt(string plainText, string key, string iv, bool isBase64 = true)
    {
        using Aes aesAlg = Aes.Create();
        aesAlg.Key = isBase64 ? Convert.FromBase64String(key) : Encoding.UTF8.GetBytes(key);
        aesAlg.IV = isBase64 ? Convert.FromBase64String(iv) : Encoding.UTF8.GetBytes(iv);

        ICryptoTransform encryptor = aesAlg.CreateEncryptor(aesAlg.Key, aesAlg.IV);

        using MemoryStream msEncrypt = new MemoryStream();
        using (CryptoStream csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write))
        {
            using (StreamWriter swEncrypt = new StreamWriter(csEncrypt))
            {
                swEncrypt.Write(plainText);
            }
        }

        var resultArray = msEncrypt.ToArray();
        return Convert.ToBase64String(resultArray, 0, resultArray.Length);
    }

    /// <summary>
    /// AES解密
    /// </summary>
    public static string AesDecrypt(string cipherText, string key, string iv, bool isBase64 = true)
    {
        using Aes aesAlg = Aes.Create();
        aesAlg.Key = isBase64 ? Convert.FromBase64String(key) : Encoding.UTF8.GetBytes(key);
        aesAlg.IV = isBase64 ? Convert.FromBase64String(iv) : Encoding.UTF8.GetBytes(iv);

        ICryptoTransform decryptor = aesAlg.CreateDecryptor(aesAlg.Key, aesAlg.IV);

        using MemoryStream msDecrypt = new MemoryStream(Convert.FromBase64String(cipherText));
        using CryptoStream csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read);
        using StreamReader srDecrypt = new StreamReader(csDecrypt);
        return srDecrypt.ReadToEnd();
    }
}